"""New chat message model (independent from legacy chat_history)."""

from __future__ import annotations

from sqlalchemy import (
    Integer,
    String,
    Text,
    DateTime,
    func,
    Boolean,
    JSON,
    Column,
    ForeignKey,
)
from app.database import Base


class ChatMessage(Base):
    __tablename__ = "chat_messages"

    id = Column(Integer, primary_key=True, index=True)
    session_id = Column(
        Integer,
        ForeignKey("chat_sessions.id", ondelete="CASCADE"),
        index=True,
        nullable=False,
    )
    user_id = Column(Integer, index=True, nullable=True)  # null for assistant/system
    role = Column(
        String(32), nullable=False, index=True
    )  # user / assistant / system / tool / error
    content = Column(Text, nullable=False, default="")
    content_type = Column(String(32), default="text", nullable=False)
    model_name = Column(String(128), nullable=True)
    seq = Column(Integer, nullable=False)  # per-session incremental sequence
    parent_message_id = Column(
        Integer, ForeignKey("chat_messages.id"), nullable=True, index=True
    )
    is_final = Column(Boolean, default=True, nullable=False)
    hidden = Column(Boolean, default=False, nullable=False)
    tokens_in = Column(Integer, default=0, nullable=False)
    tokens_out = Column(Integer, default=0, nullable=False)
    latency_ms = Column(Integer, default=0, nullable=False)
    citations = Column(JSON, nullable=True)
    tool_name = Column(String(128), nullable=True)
    tool_args = Column(JSON, nullable=True)
    tool_output = Column(JSON, nullable=True)
    meta = Column(JSON, nullable=True)
    created_at = Column(
        DateTime(timezone=True), server_default=func.now(), nullable=False
    )
    updated_at = Column(
        DateTime(timezone=True),
        server_default=func.now(),
        onupdate=func.now(),
        nullable=False,
    )

    def __repr__(self) -> str:  # pragma: no cover
        return f"<ChatMessage id={self.id} session_id={self.session_id} role={self.role} seq={self.seq}>"
